import store from '../store/index'
import Toast from '@/wxcomponents/@vant/toast/toast'

export function request(info) {
	let promise = new Promise(function(resolve, reject) {
		if (info.methods.toUpperCase() === "GET") {
			for (var v in info.data) {
				if (info.data[v] == undefined) {
					delete info.data[v];
				}
			}
		}
		// if(!requestCurrent(info)){
		// 	uni.hideToast()	
		// 	uni.hideLoading()
		// 	reject("尚未登录授权");
		// 	return
		// };
		//debugger
		let header = {
			"token": '',
			"Content-Type": info.ContentType || "application/json; charset=UTF-8",
			"X-Time": Date.parse(new Date()) / 1000,
		};
		if (store.state.user.token) {
			header['Authorization'] = 'Bearer ' + store.state.user.token;
		}

		//debugger
		uni.request({
			url: process.env.BASEURL + info.url,
			data: info.data,
			method: info.methods || "GET",
			dataType: info.dataType || "JSON",
			header: header,
			success: function(res) {
				res.data = JSON.parse(res.data)
				if (res.statusCode !== 200) {
					if (res.data.msg) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2000
						})
					} else {
						handleError(res, reject)
					}
					reject(res)
				}
				/* res.data.data = JSON.parse(res.data.data) */
				resolve(res.data);
			},
			fail: function(err) {
				reject(err);
			}
		});
	})
	return promise;
}


function handleError(data, reject) {
	if (data.statusCode == 500) {
		uni.showToast({
			title: '系统正在开小差，请稍后重试',
			icon: 'none',
			duration: 2000
		});
		reject(data)
		return
	} else if (data.statusCode == 421) {
		uni.showToast({
			icon: 'none',
			title: '登录失败了，请稍后重试',
			duration: 2000
		});
		reject(data)
		return
	} else if (data.statusCode == 429) {
		uni.showToast({
			title: '访问过于频繁啦，请稍后',
			icon: 'none',
			duration: 2000
		});
		reject(data)
		return
	} else {
		uni.showToast({
			icon: 'none',
			title: '系统正在开小差，请稍后重试',
			duration: 2000
		});
		reject(data)
		return
	}
}